﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BySoft.Web.Utility;
using BySoft.Server.Common;
using BySoft.Server.Consts;
using BySoft.Server.Common.Entity;
using BySoft.Server.Business;
using BySoft.Server.Common.Enum;
using OneSoft.EntityCore;
using BySoft.Web.Site;

namespace BySoft.Web.Site.SysManage
{
    public partial class FormCheckEdit : AuthBasePage
    {
        #region 属性定义

        private DataTable DtFormCheckData
        {
            get
            {
                if (null == Session["FormCheckData"])
                {
                    return CreateDT();
                }
                else
                {
                    return (DataTable)Session["FormCheckData"];
                }
            }
            set
            {
                Session["FormCheckData"] = value;
            }
        }

        private DataTable CreateDT()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("FormCheckDetailID");//0
            dt.Columns.Add("CheckUser");//1
            dt.Columns.Add("CheckUserName");//1
            dt.Columns.Add("OrderNum");//2
            dt.Columns.Add("IsEnd");//2
            dt.Columns.Add("IsDel");//2
            dt.Columns.Add("IsNew");//2
            return dt;
        }
        #endregion

        #region 初始化及绑定控件
        private void InitData()
        {
            DtFormCheckData = null;
            SetControlAttr(new SysFormauditEntity(), tBase);
            InitHead(hidFormCheckID.Value);
            BindData();
        }

        private void InitHead(string strCode)
        {
            DataTable dt = SysFormcheck.SelectHead(strCode);
            DataRow row = dt.Rows[0];
            chkIsCheck.Checked = CommonMethod.GetString(row["IsCheck"]).Equals("1");
            DataTable dttemp = CreateDT();
            foreach (DataRow dr in dt.Rows)
            {
                DataRow rowNew = dttemp.NewRow();
                rowNew["FormCheckDetailID"] = CommonMethod.GetString(dr["FormCheckDetailID"]);
                rowNew["CheckUser"] = CommonMethod.GetString(dr["CheckUser"]);
                rowNew["CheckUserName"] = CommonMethod.GetString(dr["UserName"]);
                rowNew["OrderNum"] = CommonMethod.GetString(dr["OrderNum"]);
                rowNew["IsEnd"] = CommonMethod.GetString(dr["IsEnd"]);
                rowNew["IsDel"] ="-1";
                rowNew["IsNew"] ="-1";
                dttemp.Rows.Add(rowNew);
            }
            dttemp.AcceptChanges();
            DtFormCheckData = dttemp; 
        }

        #endregion

        #region 控件事件
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                hidFormCheckID.Value = UIHelper.GetQueryStringValue("id");
                grdResult.Style.Add("word-break", "keep-all");
                grdResult.Style.Add("word-wrap", "normal");
                InitData();
            }
            Master.ValidationGroup = "gSubmit";
            UIHelper.RunScript(this.UpdatePanel1, "Refreashtab();");
        }

        private void GetGridViewData()
        {
            DataTable dttemp = DtFormCheckData.Copy();
            int i = 0;
            foreach (GridViewRow gvr in grdResult.Rows)
            {
                i++;
                Label lblFormCheckDetailID = gvr.FindControl("lblFormCheckDetailID") as Label;
                if (lblFormCheckDetailID == null || string.IsNullOrEmpty(lblFormCheckDetailID.Text.Replace("&nbsp;", "")))
                {
                    continue;
                }
                DropDownList ddlCheckUser = gvr.FindControl("ddlCheckUser") as DropDownList;
                Label lblLevel = gvr.FindControl("lblLevel") as Label;
                DataRow[] drs = dttemp.Select("FormCheckDetailID='" + lblFormCheckDetailID.Text + "' ");
                if (drs != null && drs.Length > 0)
                {
                    DataRow drItem = drs[0];
                    drItem["CheckUser"] = ddlCheckUser.SelectedValue;
                    drItem["OrderNum"] = GetGridViewString(lblLevel);
                    drItem["IsEnd"] = "0";
                    if (i == grdResult.Rows.Count)
                    {
                        drItem["IsEnd"] = "1";
                    } 
                }
                else
                {
                    DataRow row = dttemp.NewRow();
                    row["FormCheckDetailID"] = GetGridViewString(lblFormCheckDetailID);
                    row["CheckUser"] = GetGridViewString(ddlCheckUser);
                    row["OrderNum"] = GetGridViewString(lblLevel);
                    row["IsEnd"] = "0";
                    if (i == grdResult.Rows.Count)
                    {
                        row["IsEnd"] = "1";
                    } 
                    dttemp.Rows.Add(row);
                }
            }
            dttemp.AcceptChanges();
            DtFormCheckData = dttemp;
        }

        private void BindData()
        {
            DataView dv = new DataView(DtFormCheckData);
            dv.RowFilter = "IsDel<>'1'";
            DataTable dt = dv.ToTable(); 
            if (dt.Rows.Count > 0)
            {
                grdResult.DataSource = dt;
                grdResult.DataBind();
                SetControlAttr(new SysFormauditdetailEntity(), grdResult);
            }
            else
            {
                UIHelper.BindEmptyGridView(grdResult, CreateDT());
            }
            UIHelper.RunScript(this.UpdatePanel1, "iframeAutoFit();");
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            GetGridViewData();
            DataTable dttemp = DtFormCheckData.Copy();
            DataRow row = dttemp.NewRow();
            row["FormCheckDetailID"] = Guid.NewGuid().ToString();
            row["IsDel"] ="-1";
            row["IsNew"] = "1";
            dttemp.Rows.Add(row);
            DtFormCheckData = dttemp;
            BindData();
        }

        protected void btnAddh_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected DataTable BindCheckUser()
        {
            DataTable dt = SysUser.Select();
            DataRow row = dt.NewRow();
            row["UserID"] = "";
            row["UserName"] = "请选择...";
            dt.Rows.Add(row);
            return dt;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            GetGridViewData();
            if (!ValidateData())
            {
                return;
            }
            SysFormcheckEntity entity = new SysFormcheckEntity();
            entity.FormCheckID = CommonMethod.ConvertToDecimal(hidFormCheckID.Value);
            entity.IsCheck = chkIsCheck.Checked ? "1" : "0"; 
            entity.ModifyUserId = CurrentUser.UserID;
            entity.ModifyUserName = CurrentUser.UserName;
            entity.ModifyDate = DateTime.Now;

            List<SysFormcheckdetailEntity> lstbody = new List<SysFormcheckdetailEntity>();

            SysFormcheck.SaveOrUpdate(entity, "Update", lstbody, DtFormCheckData);
            base.LogAction(BaseEnum.ActionType.Modify, entity.FormCheckID.ToString(), true, null, new EntityBase[] { entity });
            DtFormCheckData = null;
            UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../SysManage/FormCheckList.aspx");
        }

        protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "del")
            {
                string str = e.CommandArgument.ToString();
                int iDel = CommonMethod.ConvertToInt(str);
                GetGridViewData();
                DataTable dt = DtFormCheckData.Copy();
                DataRow[] drs = dt.Select("FormCheckDetailID='" + str + "'");

                if (drs != null && drs.Length>0)
                {
                    drs[0]["IsDel"] = "1";
                } 
                DtFormCheckData = dt.Copy();
                BindData();
                UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
            }
        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                #region 删除绑定
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete +

        "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
                #endregion

                string strCheckUser = ((DataTable)((GridView)sender).DataSource).Rows[e.Row.RowIndex]["CheckUser"].ToString().Trim();
                DropDownList ddlCheckUser = e.Row.FindControl("ddlCheckUser") as DropDownList;
                if (ddlCheckUser != null)
                {
                    ddlCheckUser.SelectedValue = strCheckUser;
                }
            }
        }
        #endregion

        #region 本地方法
        private bool ValidateData()
        {
            string strMention = "";
            DataTable dt = DtFormCheckData.Copy();
            foreach (DataRow dr in dt.Rows)
            {
                string strCheckUser = CommonMethod.GetString(dr["CheckUser"]);
                if (string.IsNullOrEmpty(strCheckUser))
                {
                    strMention += "请选择审核人员！";
                }
            }
            if (string.IsNullOrEmpty(strMention))
            {
                return true;
            }
            else
            {
                UIHelper.AlertMessage(this.Page, strMention);
                return false;
            }
        }
        #endregion
    }
}

